<?php

use Biz\cache\samsungActivity\SamsungActivityCache;
use Biz\model\SamsungActivity\SamsungJoinUserListModel;
use Biz\model\SamsungActivity\SamsungVoteRecordModel;
use Biz\service\SamsungActivity\SamsungJoinUserListService;
use Doraemon\tools\HhzClient;
use Doraemon\tools\Ip;
use Doraemon\tools\Log;

class VoteAction extends ActionPlugin
{
    const USER_LEVEL = self::LEVEL_NOTHING;


    /**
     * @throws \Exception
     */
    public function main()
    {
        $currUid = $this->uid;
        $artworkId = $this->getRequest()->getPost('id', 0);//作品id
        $secretId = $this->getRequest()->getPost('secret_id', '');//加密id
        try {

            if (SamsungJoinUserListModel::isCanVote() == 0) {
                throw new Exception('投票已结束！');
            }
            // 单个ip每日投票总数限制
            $requestIp = Ip::getClientIp();
            if (SamsungActivityCache::getTodayIpVote($requestIp) >= SamsungVoteRecordModel::IP_DAY_VOTE_LIMIT) {
                //钉钉机器人消息通知
                \Doraemon\service\DingTalkAlert::sendTextMsg(\Doraemon\service\DingTalkAlert::BIZ_BRAND_ACTIVITY_SAMSUNG_VOTE,
                    implode("\n", [
                        "secretId：".$secretId,
                        "uid：".$currUid,
                        "artworkId：".$artworkId,
                        "ip：".Ip::getClientIp() ?? 0,
                        "此ip投票数：".SamsungActivityCache::getTodayIpVote($requestIp),
                        "ip每日投票限制：".SamsungVoteRecordModel::IP_DAY_VOTE_LIMIT,
                    ])
                    , false, ['renzhifan']);
                throw new Exception('抱歉,您的投票不合规！');
            }
            //判断当前作品id是否为可投票作品id
            $artworkIdShow = SamsungJoinUserListService::getShowArtworkData();
            if (!in_array($artworkId, array_column($artworkIdShow, 'id'))) {
                throw new Exception('投票作品不合规！');
            }
            if ($currUid > 0) {
                $uid = $currUid;
            } else {
                $uid = SamsungJoinUserListService::getSecretId();
                if ($secretId != $uid) {
                    throw new Exception('非法投票！');
                }
            }
            //每个用户每天限投10票
            $userTodayVoteCnt = count(SamsungActivityCache::getTodayUserVote($uid));
            if ($userTodayVoteCnt >= SamsungVoteRecordModel::USER_DAY_VOTE_LIMIT) {
                throw new Exception('今日次数已用完，明天再来吧！');
            }
            //每个用户每个作品每天限投1票
            $userVoteRes = SamsungActivityCache::userVote($uid, $artworkId);
            if ($userVoteRes == 1) { //1：用户投票成功
                //组装数据
                $data = [
                    'obj_id' => $artworkId,
                    'uid' => $uid,
                    'vote_day' => date('Ymd'),
                    'ua' => $_SERVER['HTTP_USER_AGENT'],
                    'ip' => Ip::getClientIp(),
                    'device_id' => HhzClient::getDid(),
                ];

                //每个作品每天最多1万票，超出1万票不再记录
                $artworkTodayVoteCnt = SamsungActivityCache::getTodayArtworkVote($artworkId);
                if (SamsungVoteRecordModel::ARTWORK_DAY_VOTE_LIMIT > $artworkTodayVoteCnt) {
                    //记录入库
                    SamsungVoteRecordModel::insertData($data);
                    //当日作品投票计数更新
                    SamsungActivityCache::artworkVote($artworkId);
                    //ip当日投票计数更新
                    SamsungActivityCache::ipVote(Ip::getClientIp());
                } else {
                    //不做处理只记录日志
                    Log::info('三星活动作品投票超出当日限制数据记录', $data);
                }
            } else {
                throw new Exception('您已对该作品投过票了，明天再来吧！');
            }
        } catch (Exception $exception) {

            Log::error('三星活动投票异常', [
                'currUid' => $currUid,
                'obj_id' => $artworkId,
                'secretId' => $secretId,
                'vote_day' => date('Ymd'),
                'ua' => $_SERVER['HTTP_USER_AGENT'],
                'ip' => Ip::getClientIp(),
                'device_id' => HhzClient::getDid(),
            ]);
            throw new Exception($exception->getMessage(), $exception->getCode());
        }
        $this->setSuccess([], self::API_CODE_SUCCES);


    }
}